package com.ljs.module.service.impl;

import com.ljs.module.common.DataBean;
import com.ljs.module.entity.template.joint.MethodAndParams;
import com.ljs.module.service.ScriptMethods;
import com.ljs.module.util.Util;
import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class FunctionParse extends AbstractParse<List<MethodAndParams>> {

    List<MethodAndParams> methodAndParams = new ArrayList<>();

    @Override
    public String getRegx() {
        return "Function ([\\s\\S]*?);";
    }

    @Override
    public DataBean parse(String data) {
        String function = getMatcher().group(1);
        if (StringUtils.isBlank(function)) {
            return DataBean.fail(data + "  函数不能为空");
        }
        String regx = "([\\s\\S]*?)\\(([\\s\\S]*?)\\)";
        Pattern pattern = Pattern.compile(regx);
        Matcher matcher = pattern.matcher(function);
        if (!matcher.find()) {
            return DataBean.fail(data + "  无法解析函数 " + function);
        }
        String methodName = matcher.group(1);
        String paramstr = matcher.group(2);
        if (Util.isNullOrEmpty(methodName, paramstr)) {
            return DataBean.fail(data + "  函数不能存在空值 函数名(参数1,参数2)");
        }
        methodName = methodName.trim();
        paramstr = paramstr.trim();
        String[] params = paramstr.split(",");
        Object[] paramObjects = new Object[params.length];
        Class[] classes = new Class[params.length];
        for (int i = 0; i < params.length; i++) {
            paramObjects[i] = Util.isBoolOrString(params[i].trim());
            classes[i] = paramObjects[i].getClass();
        }
        Method method = null;
        try {
            method = ScriptMethods.class.getMethod(methodName, classes);
            methodAndParams.add(new MethodAndParams(method, paramObjects));
        } catch (NoSuchMethodException e) {
            return DataBean.fail("函数:" + methodName + "，找不到或参数列表不一致" + e.getMessage());
        }
        return DataBean.success();
    }

    @Override
    public DataBean action(Map<String, Object> map) {
        ScriptMethods scriptMethods = new ScriptMethods(map);
        for (MethodAndParams methodAndParam : methodAndParams) {
            try {
                methodAndParam.getMethod().invoke(scriptMethods, methodAndParam.getParams());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return DataBean.success();
    }

    @Override
    public List<MethodAndParams> getData() {
        return methodAndParams;
    }
}
